from django.shortcuts import render

# Create your views here.


"""
获取省份信息  GET  areas/infos/
获取市,区县信息  GET areas/infos/pk/


获取省份信息的sql语句
select * from tb_areas where parent_id is NULL;

获取市的信息
select * from tb_areas where parent_id = 140000;
获取区县信息
select * from tb_areas where parent_id = 140100;

获取省份信息  GET  areas/infos/
1.获取所以省份信息
areas = Area.objects.filter(parent_id__isnull = True)
2.创建序列化器,让序列化器将对象转换为字典
serializer = AreaSerializer(areas,many=True)
3.返回响应
return Response(serializer.data)

获取市,区县信息  GET areas/infos/pk/

继承自APIView,如何实现
1.获取数据
areas = Area.objects.filter(parent_id=pk)
2.创建序列化器,让序列化器将对象转换为字典
serializer = AreaSerializer(areas,many=True)
3.返回响应
return Response(serializer.data)

"""

from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from .models import Area
from .serializers import AreaSerializer,AreaSubSerializer


"""
获取省份信息  GET  areas/infos/
获取市,区县信息  GET areas/infos/pk/
"""

class AreaViewSet(CacheResponseMixin,ReadOnlyModelViewSet):
    #因为这有缓存,所以如果要分页的话 必须先清楚缓存,或者从分页变成不分页也要清楚缓存
    pagination_class = None
    #ReadOnlyModelViewSet 是继承自GenericAPIView
    #GenericAPIView 对列表视图和详情视图做了通用支持
    #一般要设置query_set 和serializer_class

    # queryset = Area.objects.all()  #区县信息
    # queryset = Area.objects.filter(parent_id__isnull = True) #省
    def get_queryset(self):
        if self.action == 'list':
            #获取省份信息
            return Area.objects.filter(parent_id__isnull = True)
        else:
            #获取市区县信息
            return Area.objects.all()

    # serializer_class = AreaSerializer
    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return AreaSubSerializer

